package com.ts.api.http.org.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.http.org.entity.apply.OrgApplyCaiSheChengZhang;
import com.ts.api.http.org.entity.dataexchange.OrgDataExchangeCaiSheChengZhang;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMd5ConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5Apply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5DataExchange;
import org.aopalliance.aop.AspectException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 *  安心分期&彩色成长
 *
 *  @author 李源聪
 */
@ApiPlan(productId = "171", type = ApiPlanConvertType.ORG_PHONE_MD5)
public class ApiOrgPhoneMd5CaiSheChengZhang implements ApiOrgPhoneMd5ConvertHandler {

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        OrgDataExchangeCaiSheChengZhang copy = CopyUtils.copy(apiDataExchangeParameter, OrgDataExchangeCaiSheChengZhang.class);
        String json = JsonUtils.toJson(copy);
        return JsonUtils.toJson(MapUtils.newHashMap(newMap -> newMap.put("data", encryptAx(json))));
    }

    @Override
    public RespOrgPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 1000)) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        return RespOrgPhoneMd5DataExchange.ofSuc();
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        OrgApplyCaiSheChengZhang copy = CopyUtils.copy(apiApplyParameter, OrgApplyCaiSheChengZhang.class);
        if (ValidParam.isEmpty(copy.getCarInfo())){
            copy.setCarInfo("1");
        }
        if (ValidParam.isEmpty(copy.getRealEstateInfo())){
            copy.setRealEstateInfo("1");
        }
        if (ValidParam.isEmpty(copy.getProvidentFund())){
            copy.setProvidentFund("1");
        }
        if (ValidParam.isEmpty(copy.getSocialSecurity())){
            copy.setSocialSecurity("1");
        }
        if (ValidParam.isEmpty(copy.getInsurancePolicy())){
            copy.setInsurancePolicy("1");
        }
        String json = JsonUtils.toJson(copy);
        return JsonUtils.toJson(MapUtils.newHashMap(newMap -> newMap.put("data", encryptAx(json))));
    }

    @Override
    public RespOrgPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 1000)) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        return RespOrgPhoneMd5Apply.ofSuc();
    }

    /**
     * 加密
     * @param content 需要加密的内容
     */
    public static String encryptAx(String content) {

        try {
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, genKey());// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return parseByte2HexStr(result); // 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param content 待解密内容
     */
    public static String decryptAx(String content) {

        try {
            byte[] decryptFrom = parseHexStr2Byte(content);
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, genKey());// 初始化
            byte[] result = cipher.doFinal(decryptFrom);
            return new String(result); // 加密
        } catch (Exception e) {
            throw new AspectException("数据解密失败");
        }
    }

    /**
     * 加密
     * @param content 需要加密的内容
     */
    public static String encrypt(String content) {

        try {
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, genKey());// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return parseByte2HexStr(result); // 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param content 待解密内容
     */
    public static String decrypt(String content) {

        try {
            byte[] decryptFrom = parseHexStr2Byte(content);
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, genKey());// 初始化
            byte[] result = cipher.doFinal(decryptFrom);
            return new String(result); // 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据密钥获得 SecretKeySpec
     */
    private static SecretKeySpec genKey() {

        String strKey = "4987cd682c336e06142f2eb0722dfc05e5741c42df6171067c7c118d297743cc";// 加密解密密钥
        byte[] enCodeFormat = {0};
        ;
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(strKey.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            enCodeFormat = secretKey.getEncoded();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new SecretKeySpec(enCodeFormat, "AES");
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     */
    private static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
